def set_env():
    import os
    import sys
    import django

    project_path = os.path.abspath(os.path.realpath(__file__) + r"/../../../")

    # 添加工程名
    sys.path.append(project_path)
    # 工程路径
    os.chdir(project_path)
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Box.settings")
    django.setup()


def route_del(mac):
    """
    路由器恢复出厂设置时触发，更新数据库
    1、回收 tos
    2、该路由器的服务器地址为空
    :param mac: 路由器 Mac 地址
    :return:
    """
    set_env()
    from system.models import Router
    try:
        route_obj = Router.get_mac(mac)
        tos_list = eval(route_obj[0].tos_list)  # tos 列表

        device_obj = route_obj[0].terminal_set.all()

        for device in device_obj:
            tos_list.append(device.tos)

        route_obj.update(tos_list=tos_list)
        route_obj.update(server_addr="")
    except Exception as e:
        print('更新数据库出现错误：', e)


def check_mac_is_exist(mac: str, user: object):
    """
    检查 Mac 是否绑定其他用户，除开当前登陆用户
    :param mac: mac 地址
    :param user: 当前登陆用户对象
    :return:
    """
    set_env()
    from system.models import Router

    route_obj = Router.get_mac(mac)

    if route_obj.count():
        if route_obj[0].user != user:
            ret = {'code': 10005, 'msg': '该 Mac 已被其他人绑定，是否继续登陆？'}
        else:
            ret = {'code': 10006, 'msg': '该 Mac 属于当前用户'}

    else:
        ret = {'code': 10007, 'msg': '数据库中不存在'}

    return ret


def get_mac_info(user_id):
    """
    获取路由器相关详细信息
    :param user_id:
    :return:
    """
    set_env()
    from system.models import Router

    result_list = []
    route_obj = Router.get_route(user_id)
    if route_obj:
        for i in route_obj:
            tunnel = '通道1' if str(i.tunnel) == '0' else ''

            if not i.server_addr:
                server_addr = '未绑定'
                bind_time = ''
                tunnel = ''
            else:
                server_addr = i.server_addr
                bind_time = str(i.bind_time)

            result_list.append({
                i.mac_addr: [i.name, server_addr, tunnel, bind_time]
            })

    return result_list


def structure_route(route_obj):
    """构造用户路由器信息"""
    set_env()

    result_list = []

    if route_obj:
        for i in route_obj:
            tunnel = '通道1' if str(i.tunnel) == '0' else ''

            if not i.server_addr:
                server_addr = '未绑定'
                bind_time = ''
                tunnel = ''
            else:
                server_addr = i.server_addr
                bind_time = (i.bind_time).strftime('%Y-%m-%d %H:%M:%S')

            result_list.append({
                'name': i.name,
                'mac': i.mac_addr,
                'status': '-',
                'server': server_addr,
                'tunnel': tunnel,
                'bind_time': bind_time
            })

    return result_list


def create_route(save_dic):
    """创建路由"""
    set_env()
    from system.models import Router

    Router.create(save_dic)


def get_account_list(user_id):
    """
    获取用户申请账户列表
    :return:
    """
    set_env()
    from system.models import ApplyAccount

    account_list = []
    accounts = ApplyAccount.objects.filter(user_id=user_id)

    try:
        for account in accounts:
            apply_time = account.apply_time
            expire_time = account.expire_time

            if account.status == 0:
                status = "待审核"
            elif account.status == 1:
                status = "已审核"
            else:
                status = "未通过"

            account_list.append({
                'id': account.id,
                'name': account.name,
                'type': account.client_type,
                'apply_time': apply_time.strftime('%Y-%m-%d'),
                'expire_time': expire_time.strftime('%Y-%m-%d'),
                'last_day': (expire_time - apply_time).days + 1,
                'status': status
            })
    except Exception as e:
        print(e)
        pass

    return account_list


def get_all_account(condition, start, end):
    """
    获取所有账户，审核、待审核
    :param condition: 过滤条件
    :param start:
    :param end:
    :return:
    """
    set_env()
    from system.models import ApplyAccount

    account_list = []
    accounts = ApplyAccount.objects.filter(**condition).all()[start:end]

    try:
        for account in accounts:
            apply_time = account.apply_time
            expire_time = account.expire_time

            if account.status == 0:
                status = "待审核"
            elif account.status == 1:
                status = "已审核"
            else:
                status = "未通过"

            account_list.append({
                'id': account.id,
                'name': account.name,
                'user': account.user.username,
                'type': account.client_type,
                'apply_time': apply_time.strftime('%Y-%m-%d'),
                'expire_time': expire_time.strftime('%Y-%m-%d'),
                'last_day': (expire_time - apply_time).days + 1,
                'status': status
            })
    except Exception as e:
        pass

    return account_list


def insert_line(path):
    """插入线路"""
    set_env()
    import csv
    from django.db import IntegrityError
    from system.models import Line

    try:
        with open(path, encoding='gbk') as f:
            f_csv = csv.DictReader(f)
            for row in f_csv:
                Line.objects.update_or_create(
                    ppp_usr=row.get('ppp_usr'),
                    peer=row.get('tun_pubkey'),
                    end_point=row.get('endpoint').split('//')[1].split(':')[0],
                    city=row.get('city'),
                    operator=[j[0] for j in Line.operator_choices if j[1] == row.get('isp')][0],
                    province=row.get('province'),
                    netns=row.get('netns'),
                )

        ret = True
    except IntegrityError as e:
        ret = False

    return ret
